/**
 * Main application file
 */

'use strict';

// Set default node environment to development production
process.env.NODE_ENV = process.env.NODE_ENV || 'development';

var express = require('express');
var config = require('./config/environment');
var sqldb = require('./sqldb');
var moment = require('moment');

console.info('----------------node.js------------------');
console.info(process.env.NODE_ENV);
console.info(process.env.TYPE);

moment.locale('zh-cn');

// Setup server
var app = express();
var server = require('http').createServer(app);

var socketio = require('socket.io')(server);

var socketRedis = require('socket.io-redis');
var pubRedisClient = require('redis').createClient(config.socketRedis);
var subRedisClient = require('redis').createClient(config.socketRedis);
socketio.adapter(socketRedis({
    pubClient: pubRedisClient,
    subClient: subRedisClient
}));

require('./api/global/socketio')(socketio);

require('./config/express')(app);

require('./routes')(app);

function startServer() {
    // Start server
    server.listen(config.port, config.ip, function() {
        console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
    });

    require('./api/global/cron')();

    // // 如果是开发环境，直接引入
    // if (config.env === 'development') {
    //     require('./api/global/cron')();
    // } else {
    //     // 如果不是开发环境，根据类型，是否要启动任务进程
    //     if (process.env.TYPE === 'cron') {
    //         require('./api/global/cron')();
    //     }
    // }
}

sqldb.sequelize.sync({
        // force: true
        force: false
    })
    .then(startServer)
    .catch(function(err) {
        console.log('Server failed to start due to error: %s', err);
    });


// Expose app
exports = module.exports = app;